// pages/03setup/02setPrinter/setPrinter.js
var app = getApp()
var appData = app.globalData
Page({
    data: {
        defaultPrinter: '',
        ble: [],
        bleInitOk: false,
        localBleOk: false,
    },

    onLoad: function (options) {
        var storBLE = wx.getStorageSync('ble_printer')
        if (storBLE) {
            this.setData({ defaultPrinter: storBLE })
        }else{
            this.getDefaultPrinter()
        }
        console.log('所有缓存：', wx.getStorageInfoSync(), 'this.data', this.data)
        if (wx.openBluetoothAdapter) {
            this.initBLEAdapter()
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    getDefaultPrinter: function () {
        var param = {
            uid: appData.shopInfo.shopInfo.userid,
        }
        var that = this
        app.getJsonData('api/admin/ble_printer_save.php', param, function (res) {
            console.log('蓝牙设备设置返回res', res)
            that.setData({ defaultPrinter: res.data })
            wx.setStorageSync('ble_printer', res.data)
        })
    },

    initBLEAdapter: function () {
        var that = this
        wx.openBluetoothAdapter({
            success: function (res) {
                //that.onBluetoothAdapterStateChange()
                console.log('1.蓝牙初始化成功', res)
                that.setData({ bleInitOk: true })
                that.searchBLE()
                that.getLocalBLEState()
            },
            fail: function (res) {
                wx.showModal({
                    title: '提示',
                    content: '蓝牙初始化失败，请检查重试！',
                })
            },
        })
    },

    getLocalBLEState: function () {
        var that = this
        wx.getBluetoothAdapterState({
            success: function (res) {
                that.setData({ localBleOk: true })
                console.log('本机蓝牙可用res', res)
            },
            fail: function (res) {
                console.log('本机蓝牙不可用res', res)
                wx.showModal({
                    title: '提示',
                    content: '本机蓝牙不可用，请检查！',
                })
            },
        })
    },

    searchBLE: function () {
        var that = this
        wx.startBluetoothDevicesDiscovery({
            services: [],
            success: function (res) {
                that.listenFoundBLE()
            },
            fail: function (res) {
                wx.showModal({
                    title: '提示',
                    content: '蓝牙设备搜索失败，请重试！',
                })
            },
        })
    },

    listenFoundBLE: function () {
        var that = this
        var i = 0
        wx.onBluetoothDeviceFound(function (res) {
            i++
            console.log('发现第' + i + '个蓝牙res', res)
            console.log('res.length==' + res.length)
            var sys = wx.getSystemInfoSync()
            if (sys.platform == 'devtools') {
                if (!that.isExist(res[0])) {
                    var bleArr = that.data.ble
                    bleArr.push(res[0])
                    that.setData({ ble: bleArr })
                }
            } else {
                if (!that.isExist(res.devices[0])) {
                    var bleArr = that.data.ble
                    bleArr.push(res.devices[0])
                    that.setData({ ble: bleArr })
                }
            }
            //that.listBLEDevices()
            that.stopSearchBLE()
        })
    },

    isExist: function (obj) {
        var bleArr = this.data.ble
        for (var i = 0; i < bleArr.length; i++) {
            console.log('obj.name==' + obj.name + ',bleArr[' + i + '].name==' + bleArr[i].name)
            if (obj.name == bleArr[i].name) return true
        }
        return false
    },

    stopSearchBLE: function () {
        wx.stopBluetoothDevicesDiscovery({
            success: function (res) {
                console.log('蓝牙搜索停止了')
            },
            fail: function (res) { },
        })
    },

    // listBLEDevices: function () {
    //     wx.getBluetoothDevices({
    //         services: [],
    //         success: function (res) {
    //             console.log('搜索到的所有蓝牙res', res)
    //         },
    //         fail: function (res) { },
    //         complete: function (res) { },
    //     })
    // },

    setBLEDevice: function (e) {
        var ble = this.data.ble[e.currentTarget.id]
        var param = {
            sql: 'update',
            uid: appData.shopInfo.userid,
            ble_printer: ble.deviceId
        }
        var that = this
        app.getJsonData('api/admin/ble_printer_save.php', param, function (res) {
            console.log('蓝牙设备设置返回res', res)
            wx.showToast({
                title: res.message,
            })
            if (res.code == 0) {
                wx.setStorageSync('ble_printer', ble.deviceId)
                that.setData({ defaultPrinter: ble.deviceId})
                console.log('所有缓存：', wx.getStorageInfoSync(),'this.data',that.data)
            }

        })
    }


})